package com.jiumi.api.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jiumi.api.base.BaseApiController;
import com.jiumi.api.entity.CalculatorDo;
import com.jiumi.baseconfig.domain.*;
import com.jiumi.baseconfig.service.*;
import com.jiumi.common.config.AliConfig;
import com.jiumi.common.config.JiumiConfig;
import com.jiumi.common.constant.CacheConstants;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.domain.entity.SysDictData;
import com.jiumi.common.core.page.TableDataInfo;
import com.jiumi.common.core.redis.RedisCache;
import com.jiumi.common.utils.DictUtils;
import com.jiumi.common.utils.SMSCode;
import com.jiumi.common.utils.file.FileUploadUtils;
import com.jiumi.system.service.ISysConfigService;
import com.jiumi.system.service.ISysDictDataService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lun.zhang
 * @create 2022/11/3 9:56
 */
@RequestMapping("/api")
@RestController
public class CommonApiController extends BaseApiController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBaseBannerService baseBannerService;

    @Autowired
    private IBaseTextContentService baseTextContentService;

    @Autowired
    private IBaseGoodsService baseGoodsService;

    @Autowired
    private IBaseCityInfoService cityInfoService;

    @Autowired
    private IBaseServiceTypeService baseServiceTypeService;

    @Autowired
    private ICalcConfigService calcConfigService;

    @Autowired
    private IBaseUserService userInfoService;

    @Autowired
    private IBaseUserResumeService baseUserResumeService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IBusinessConfigService businessConfigService;

    @Autowired
    private IBaseLablesService baseLablesService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseCompanyAccountService baseCompanyAccountService;
    /**
     * 获取验证码
     */
    @GetMapping("/noAuth/getPhoneCode")
    public AjaxResult getPhoneCode(@RequestParam(value = "phone", required = true) String phone) {
        AjaxResult result = null;
        try {
            result = SMSCode.sendSms(redisCache, phone);
        } catch (Exception e) {
            e.printStackTrace();
            result = AjaxResult.error(e.getMessage());
        }
        return result;
    }

    @PostMapping("/noAuth/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = JiumiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = AliConfig.getImgPrefix() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("name", file.getOriginalFilename());
            ajax.put("fileName", url);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询轮播图列表
     */
    @GetMapping("/noAuth/getBannerList")
    public AjaxResult getBannerList(@RequestParam(value = "type", required = true) String type) {
        BaseBanner banner = new BaseBanner();
        banner.setCategoryType(type);
        banner.setStatus("Y");
        List<BaseBanner> list = baseBannerService.selectBaseBannerList(banner);
        return AjaxResult.success(list);
    }

    @GetMapping("/noAuth/getLabelData")
    public AjaxResult getLabelData() {
        BaseLables param=new BaseLables();
        List<BaseLables> labelList= baseLablesService.selectBaseLablesList(param);
        return AjaxResult.success(labelList);
    }

    @GetMapping("/noAuth/getProtocolDetail")
    public AjaxResult getProtocolDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseTextContent text = baseTextContentService.selectBaseTextContentById(id);
        return AjaxResult.success(text);
    }

    @ApiOperation("获取字典")
    @GetMapping("/noAuth/queryDictLabels")
    public AjaxResult queryDictLabels(@RequestParam(value = "type", required = true) String type) {
        List<SysDictData> list = DictUtils.getDictCache(type);
        if (list == null || list.size() == 0) {
            return AjaxResult.error("未查询到数据");
        }
        return AjaxResult.success(list);
    }

    @ApiOperation("获取字典标签")
    @GetMapping("/noAuth/queryLabelData")
    public AjaxResult queryLabelData() {
        SysDictData param=new SysDictData();
        param.setStatus("0");
        List<SysDictData> dictData= dictDataService.selectDictDataList(param);
        JSONArray array=new JSONArray();
        dictData.stream().forEach(data->{
            JSONObject obj=new JSONObject();
            obj.put("dictType",data.getDictType());
            obj.put("dictLabel",data.getDictLabel());
            obj.put("dictValue",data.getDictValue());
            array.add(obj);
        });
        return AjaxResult.success(array);
    }

    @ApiOperation("获取兑换商品列表")
    @GetMapping("/noAuth/getExchangeGoodsList")
    public TableDataInfo getExchangeGoodsList() {
        BaseGoods param = new BaseGoods();
        param.setStatus("01");
        startPage();
        List<BaseGoods> goodsList = baseGoodsService.selectBaseGoodsList(param);
        return getDataTable(goodsList);
    }


    @GetMapping("/noAuth/getGoodsInfo")
    public AjaxResult getGoodsInfo(@RequestParam("id") Long id) {

        BaseGoods baseGoods = baseGoodsService.selectBaseGoodsById(id);
        return AjaxResult.success(baseGoods);
    }

    @GetMapping("/noAuth/getCitySelectData")
    public AjaxResult getCitySelectData(BaseCityInfo cityInfo) {

        return AjaxResult.success(cityInfoService.buildDeptTreeSelect(cityInfoService.selectBaseCityInfoList(cityInfo)));
    }

    @GetMapping("/noAuth/getCitySortData")
    public AjaxResult getCitySortData() {
        BaseCityInfo param=new BaseCityInfo();
        param.setParentCode("0000");
        List<BaseCityInfo> cityData= cityInfoService.selectBaseCityInfoList(param);
        JSONArray array=new JSONArray();
        Map<String,List<BaseCityInfo>> data=cityData.stream().collect(Collectors.groupingBy(BaseCityInfo::getFirst));
        return AjaxResult.success(data);
    }

    @GetMapping("/noAuth/getServiceType")
    public AjaxResult getServiceType() {
        BaseServiceType param=new BaseServiceType();
        param.setUseableFlag("Y");
        List<BaseServiceType> list= baseServiceTypeService.selectBaseServiceTypeList(param);
        return AjaxResult.success(list);
    }

    @GetMapping("/noAuth/getCalcConfigData")
    public AjaxResult getCalcConfigData() {
        List<SysDictData> dictList= DictUtils.getDictCache("base_measure_type");
        List<CalcConfig> configList= calcConfigService.selectCalcConfigList(new CalcConfig());
        List dataResult=new ArrayList();
        List<SysDictData> roleList=DictUtils.getDictCache("base_calc_role_type");
        for(SysDictData dictData : roleList){
            JSONObject obj=new JSONObject();
            obj.put("roleType",dictData.getDictValue());
            obj.put("roleName",dictData.getDictLabel());
            obj.put("roleSalary",Integer.parseInt(dictData.getRemark()));
            List<CalculatorDo> result=new ArrayList<>();
            dictList.stream().forEach(dict->{
                CalculatorDo calc=new CalculatorDo();
                calc.setMeasureType(dict.getDictValue());
                calc.setMeasureName(dict.getDictLabel());
                List<CalcConfig> list=configList.stream().filter(config->dict.getDictValue().equals(config.getMeasureType()) && dictData.getDictValue().equals(config.getRoleType())).collect(Collectors.toList());
                calc.setConfigList(list);
                if(list.size()>0) {
                    result.add(calc);
                }
            });
            obj.put("child",result);
            dataResult.add(obj);
        }
        return AjaxResult.success(dataResult);
    }

    @GetMapping("/noAuth/queryAuntData")
    public TableDataInfo queryAuntData(BaseUserResume user) {
        startOrderBy();
        startPage();
        List<BaseUserResume> dataList= baseUserResumeService.selectAuntUserList(user);
        return getDataTable(dataList);
    }

    @GetMapping("/noAuth/queryUserData")
    public TableDataInfo queryUserData(BaseUser user) {
        if(user.getAuthUserId()!=null) {
            BaseUser currentUser=userInfoService.selectBaseUserByUserId(user.getAuthUserId());
            BaseCompanyAccount param = new BaseCompanyAccount();
            param.setUserId(currentUser.getUserId());
            param.setCompanyId(currentUser.getCompanyId());
            param.setIsMain("Y");
            String isAdmin = "N";
            List<BaseCompanyAccount> account = baseCompanyAccountService.selectBaseCompanyAccountList(param);
            if (account.size() > 0) {
                isAdmin = "Y";
            }
            user.setIsAdmin(isAdmin);
        }
        startOrderBy();
        startPage();
        List<BaseUser> dataList= userInfoService.queryUserData(user);
        return getDataTable(dataList);
    }

    @GetMapping("/noAuth/queryCompanyData")
    public TableDataInfo queryCompanyData(BaseCompany company) {
        company.setAvailableFlag("Y");
        startPage();
        List<BaseCompany> dataList= baseCompanyService.selectBaseCompanyList(company);
        return getDataTable(dataList);
    }

    @GetMapping("/noAuth/getConfigData")
    public AjaxResult getConfigData(@RequestParam(value = "code", required = true) String code) {
        AjaxResult result=AjaxResult.success();
        String value="",label="";
        if("customerPhone".equals(code)){
            value = configService.selectConfigByKey("sys.customer.phonenumber");
            label="客服电话";
        }
        else if("clickCoolTime".equals(code)){
            BusinessConfig config= businessConfigService.selectBusinessConfigById(3L);
            value = config.getValue();
            label="打卡冷却时间";
        }
        else if("scorePercent".equals(code)){
            value = configService.selectConfigByKey("sys.customer.usescore.percent");
            label="积分使用比例";
        }
        else{
            return AjaxResult.error("传入参数错误");
        }
        result.put("itemDesc",label);
        result.put("itemName",code);
        result.put("itemValue",value);
        return result;
    }

    @GetMapping("/forceLogout/{userPhone}")
    public AjaxResult forceLogout(@PathVariable String userPhone)
    {
        String tokenKey=redisCache.getCacheObject(userPhone);
        redisCache.deleteObject(tokenKey);
        redisCache.deleteObject(userPhone);
        return AjaxResult.success();
    }

}
